# 基本配置
TARGET      := unit_test
BUILD_DIR   := ./build
SRC_DIR     := ./src
INC_DIRS    := ./inc

# 可选值: rk3588, rk3568, local (本地编译)
TARGET_PLATFORM ?= rk3568
# 可选值: rk3588, rk3568
LOCAL_PLATFORM ?= rk3568

# 交叉编译工具链配置（为空，使用系统gcc）
ifeq ($(TARGET_PLATFORM), rk3588)
    CROSS_COMPILE ?= /media/test/sde/ubuntu2204/rk3588/tl3588-evm_buildroot-2021.11_v2.2/rk3588_linux_release/prebuilts/gcc/linux-x86/aarch64/gcc-arm-10.3-2021.07-x86_64-aarch64-none-linux-gnu/bin/aarch64-none-linux-gnu-
    CFLAGS += -DTARGET_RK3588
else ifeq ($(TARGET_PLATFORM), rk3568)
    CROSS_COMPILE ?= /media/test/sde/ubuntu2204/rk3568/tl3568f-evm_v1.5/rk356x_linux_release_v1.3.1/prebuilts/gcc/linux-x86/aarch64/gcc-arm-10.3-2021.07-x86_64-aarch64-none-linux-gnu/bin/aarch64-none-linux-gnu-
    CFLAGS += -DTARGET_RK3568
else ifeq ($(TARGET_PLATFORM), local)
    $(info Building for local machine)
    CROSS_COMPILE ?= 
else
    $(error Unsupported TARGET_PLATFORM: $(TARGET_PLATFORM). Supported values: rk3588, rk3568, local)
endif
CC          := $(CROSS_COMPILE)gcc

# 本地编译增加多平台支持
ifeq ($(TARGET_PLATFORM), local)
    ifeq ($(LOCAL_PLATFORM), rk3588)
        CFLAGS += -DTARGET_RK3588
    else ifeq ($(LOCAL_PLATFORM), rk3568)
        CFLAGS += -DTARGET_RK3568
    else
        $(error Unsupported LOCAL_PLATFORM: $(LOCAL_PLATFORM). Supported values: rk3588, rk3568)
    endif
endif

# 编译选项
CFLAGS      += -Wall -Wextra -I$(INC_DIRS)
LDFLAGS     := -lm -lpthread

# 工具命令
RM          := rm -rf
MKDIR       := mkdir -p

# 自动查找源文件
SRCS        := $(shell find $(SRC_DIR) -name '*.c' 2>/dev/null)
OBJS        := $(SRCS:$(SRC_DIR)/%.c=$(BUILD_DIR)/%.o)

# 默认目标
all: $(BUILD_DIR)/$(TARGET)

# 主目标链接
$(BUILD_DIR)/$(TARGET): $(OBJS) | $(BUILD_DIR)
	$(CC) $(OBJS) -o $@ $(LDFLAGS)

# 编译源文件
$(BUILD_DIR)/%.o: $(SRC_DIR)/%.c | $(BUILD_DIR)
	@$(MKDIR) $(dir $@)
	$(CC) $(CFLAGS) -c $< -o $@

# 创建构建目录
$(BUILD_DIR):
	$(MKDIR) $@

# 清理
clean:
	$(RM) $(BUILD_DIR)

# 显示构建信息
info:
	@echo "=== 构建信息 ==="
	@echo "目标: $(TARGET)"
	@echo "编译器: $(CC)"
	@echo "源文件数量: $(words $(SRCS))"
	@echo "交叉编译工具链: $(if $(CROSS_COMPILE),$(CROSS_COMPILE),使用系统gcc)"
	@echo "================="

# 显示帮助信息
help:
	@echo "可用目标:"
	@echo "  all     - 构建应用程序"
	@echo "  clean   - 清理构建文件"
	@echo "  info    - 显示构建信息"
	@echo "  help    - 显示此帮助信息"
	@echo ""
	@echo "交叉编译示例:"
	@echo "  make CROSS_COMPILE=aarch64-linux-gnu-"

.PHONY: all clean info help
